<template>
  <div class="progress-bar-container">
    <!-- 控制按钮区域 -->
    <div class="controls">
      <!-- 播放/暂停按钮 -->
      <button @click="togglePlay" class="play-btn" :class="{ 'playing': isPlaying }">
        <svg v-if="!isPlaying" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8 5v14l11-7z" />
        </svg>
        <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
        </svg>
      </button>

      <!-- 倍速选择 -->
      <div class="speed-control">
        <select v-model="playSpeed" @change="onSpeedChange" class="speed-select">
          <option value="0.5">0.5x</option>
          <option value="1">1x</option>
          <option value="1.5">1.5x</option>
          <option value="2">2x</option>
          <option value="4">4x</option>
        </select>
      </div>
    </div>

    <!-- 进度条区域 -->
    <div class="progress-container" ref="progressContainer">
      <!-- 时间显示 -->
      <div class="time-display">
        <span class="current-time">{{ formatTime(currentTime) }}</span>
        <span class="separator">/</span>
        <span class="total-time">{{ formatTime(totalTime) }}</span>
      </div>

      <!-- 进度条 -->
      <div class="progress-track" @mousedown="onTrackMouseDown" @mousemove="onTrackMouseMove" @mouseup="onTrackMouseUp"
        @mouseleave="onTrackMouseLeave" ref="progressTrack">
        <!-- 背景轨道 -->
        <div class="track-background"></div>

        <!-- 已播放进度 -->
        <div class="track-progress" :style="{ width: progressPercentage + '%' }"></div>

        <!-- 缓冲进度 -->
        <div class="track-buffer" :style="{ width: bufferPercentage + '%' }"></div>

        <!-- 拖拽手柄 -->
        <div class="track-handle" :style="{ left: progressPercentage + '%' }" @mousedown="onHandleMouseDown"
          :class="{ 'dragging': isDragging }"></div>

        <!-- 悬停时的时间提示 -->
        <div v-if="hoverTime !== null" class="time-tooltip" :style="{ left: hoverPosition + 'px' }">
          {{ formatTime(hoverTime) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'

// Props
const props = defineProps({
  // 总时长（秒）
  duration: {
    type: Number,
    default: 100
  },
  // 当前时间（秒）
  modelValue: {
    type: Number,
    default: 0
  },
  // 缓冲进度（0-1）
  buffered: {
    type: Number,
    default: 0
  },
  // 是否自动播放
  autoPlay: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'play', 'pause', 'seek', 'speedChange'])

// 响应式数据
const isPlaying = ref(false)
const playSpeed = ref(1)
const currentTime = ref(0)
const totalTime = ref(props.duration)
const isDragging = ref(false)
const hoverTime = ref(null)
const hoverPosition = ref(0)

// DOM 引用
const progressContainer = ref(null)
const progressTrack = ref(null)

// 定时器
let playTimer = null

// 计算属性
const progressPercentage = computed(() => {
  return totalTime.value > 0 ? (currentTime.value / totalTime.value) * 100 : 0
})

const bufferPercentage = computed(() => {
  return props.buffered * 100
})

// 监听 props 变化
watch(() => props.modelValue, (newVal) => {
  if (!isDragging.value) {
    currentTime.value = newVal
  }
})

watch(() => props.duration, (newVal) => {
  totalTime.value = newVal
})

// 方法
const togglePlay = () => {
  if (isPlaying.value) {
    pause()
  } else {
    play()
  }
}

const play = () => {
  isPlaying.value = true
  emit('play')
  startPlayTimer()
}

const pause = () => {
  isPlaying.value = false
  emit('pause')
  stopPlayTimer()
}

const startPlayTimer = () => {
  stopPlayTimer()
  const interval = 1000 / (60 * playSpeed.value) // 60fps base

  playTimer = setInterval(() => {
    if (currentTime.value >= totalTime.value) {
      pause()
      return
    }

    currentTime.value += 0.1 * playSpeed.value
    if (currentTime.value > totalTime.value) {
      currentTime.value = totalTime.value
    }

    emit('update:modelValue', currentTime.value)
  }, interval)
}

const stopPlayTimer = () => {
  if (playTimer) {
    clearInterval(playTimer)
    playTimer = null
  }
}

const onSpeedChange = () => {
  emit('speedChange', playSpeed.value)
  if (isPlaying.value) {
    startPlayTimer() // 重新启动定时器以应用新速度
  }
}

// 拖拽相关方法
const getTimeFromPosition = (clientX) => {
  const rect = progressTrack.value.getBoundingClientRect()
  const percentage = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width))
  return percentage * totalTime.value
}

const onTrackMouseDown = (event) => {
  const newTime = getTimeFromPosition(event.clientX)
  seekTo(newTime)
}

const onHandleMouseDown = (event) => {
  event.stopPropagation()
  isDragging.value = true
  document.addEventListener('mousemove', onDocumentMouseMove)
  document.addEventListener('mouseup', onDocumentMouseUp)
}

const onDocumentMouseMove = (event) => {
  if (isDragging.value) {
    const newTime = getTimeFromPosition(event.clientX)
    currentTime.value = Math.max(0, Math.min(totalTime.value, newTime))
    // 立即发射更新事件以实现实时响应
    emit('update:modelValue', currentTime.value)
    emit('seek', currentTime.value)
  }
}

const onDocumentMouseUp = () => {
  if (isDragging.value) {
    isDragging.value = false
    // 拖动结束时只需要发射一次 seek 事件
    emit('seek', currentTime.value)
    document.removeEventListener('mousemove', onDocumentMouseMove)
    document.removeEventListener('mouseup', onDocumentMouseUp)
  }
}

const onTrackMouseMove = (event) => {
  if (!isDragging.value) {
    const rect = progressTrack.value.getBoundingClientRect()
    hoverPosition.value = event.clientX - rect.left
    hoverTime.value = getTimeFromPosition(event.clientX)
  }
}

const onTrackMouseUp = () => {
  // 处理轨道上的鼠标释放
}

const onTrackMouseLeave = () => {
  hoverTime.value = null
}

const seekTo = (time) => {
  currentTime.value = Math.max(0, Math.min(totalTime.value, time))
  emit('update:modelValue', currentTime.value)
  emit('seek', currentTime.value)
}

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 生命周期
onMounted(() => {
  currentTime.value = props.modelValue
  if (props.autoPlay) {
    play()
  }
})

onUnmounted(() => {
  stopPlayTimer()
  document.removeEventListener('mousemove', onDocumentMouseMove)
  document.removeEventListener('mouseup', onDocumentMouseUp)
})

// 暴露方法给父组件
defineExpose({
  play,
  pause,
  seekTo,
  togglePlay
})
</script>

<style scoped lang="scss">
.progress-bar-container {
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 66.67%;
  /* 占据屏幕三分之二 */
  min-width: 600px;
  /* 最小宽度 */
  max-width: 1200px;
  /* 最大宽度 */
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  background: #1a1a1a;
  border-radius: 8px;
  color: #ffffff;
  user-select: none;
  z-index: 1000;
}

.controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.play-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: #4a90e2;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: #357abd;
    transform: scale(1.05);
  }

  &.playing {
    background: #e74c3c;

    &:hover {
      background: #c0392b;
    }
  }
}

.speed-control {
  .speed-select {
    padding: 4px 8px;
    border: 1px solid #444;
    border-radius: 4px;
    background: #2a2a2a;
    color: #ffffff;
    cursor: pointer;
    outline: none;

    &:hover {
      border-color: #4a90e2;
    }
  }
}

.progress-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-display {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #cccccc;

  .separator {
    margin: 0 4px;
  }
}

.progress-track {
  position: relative;
  height: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;

  .track-background {
    position: absolute;
    width: 100%;
    height: 4px;
    background: #444444;
    border-radius: 2px;
  }

  .track-buffer {
    position: absolute;
    height: 4px;
    background: #666666;
    border-radius: 2px;
    z-index: 1;
  }

  .track-progress {
    position: absolute;
    height: 4px;
    background: linear-gradient(90deg, #4a90e2, #357abd);
    border-radius: 2px;
    z-index: 2;
    /* 移除过渡效果以实现实时响应 */
  }

  .track-handle {
    position: absolute;
    width: 16px;
    height: 16px;
    background: #ffffff;
    border: 2px solid #4a90e2;
    border-radius: 50%;
    z-index: 3;
    transform: translateX(-50%);
    cursor: grab;
    /* 移除过渡效果以实现实时响应 */

    &:hover,
    &.dragging {
      transform: translateX(-50%) scale(1.2);
      cursor: grabbing;
      box-shadow: 0 0 0 4px rgba(74, 144, 226, 0.3);
    }
  }

  .time-tooltip {
    position: absolute;
    bottom: 100%;
    padding: 4px 8px;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    font-size: 11px;
    border-radius: 4px;
    transform: translateX(-50%);
    margin-bottom: 8px;
    pointer-events: none;
    white-space: nowrap;
    z-index: 4;

    &::after {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      transform: translateX(-50%);
      border: 4px solid transparent;
      border-top-color: rgba(0, 0, 0, 0.8);
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .progress-bar-container {
    width: 80%;
    min-width: 500px;
  }
}

@media (max-width: 768px) {
  .progress-bar-container {
    width: 90%;
    min-width: 400px;
    flex-direction: column;
    gap: 12px;
  }

  .progress-container {
    width: 100%;
  }

  .time-display {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .progress-bar-container {
    width: 95%;
    min-width: 300px;
  }
}

// 动画效果
@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

.play-btn.playing {
  animation: pulse 2s infinite;
}

// 暗色主题适配
@media (prefers-color-scheme: light) {
  .progress-bar-container {
    background: #f5f5f5;
    color: #333333;
  }

  .speed-select {
    background: #ffffff;
    color: #333333;
    border-color: #cccccc;
  }

  .track-background {
    background: #e0e0e0;
  }

  .track-buffer {
    background: #cccccc;
  }
}
</style>